import os
import shutil

from app.config import wechat_root, source_dbs_path, decrypt_dbs_path, key, message_temp_path
from app.db.encrypt_db import EncryptDb
from app.utils import check_path


def copy_db_files():
    # 复制源文件，避免对源文件操作
    dirs = ['Message', 'Group', 'Contact', 'Group', 'Session']
    if not os.path.exists(source_dbs_path):
        print("正在拷贝数据库文件(避免对源文件操作)，请稍等...")
        check_path(source_dbs_path)

        for d in dirs:
            for f in os.listdir(os.path.join(wechat_root, d)):
                if 'backup' in f or not 'db' in f: continue
                shutil.copyfile(os.path.join(wechat_root, d, f), os.path.join(source_dbs_path, f))


def decrypt_db_file():
    # 解密db 文件
    if not os.path.exists(decrypt_dbs_path):
        print("正在解密数据库文件，请稍等...")
        check_path(decrypt_dbs_path)

        for file in os.listdir(source_dbs_path):
            if ".db" == file[-3:]:
                encrypt_db = EncryptDb(source_dbs_path, file, decrypt_dbs_path, key)
                encrypt_db.decrypt_db()


def main():
    shutil.rmtree("static/wxdata")

    # 拷贝数据库文件
    copy_db_files()

    # 解密
    decrypt_db_file()

    if not os.path.exists(message_temp_path):
        print("正在拷贝静态文件，该过程需等待数分钟，请稍等...")
        shutil.copytree(wechat_root + "Message/MessageTemp", message_temp_path)


main()
